<!-- 使用element的upload的默认上传方式 -->
<template>
  <div>
    <el-upload class="upload-demo" ref="upload" action="#" :on-change="onChange" :file-list="fileList"
      :auto-upload="false" accept=".png,.pdf,.jpg,.xlsx" multiple>
      <el-button slot="trigger" size="small" type="primary">选取附件</el-button>
      <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传附件</el-button>
      <div slot="tip" class="el-upload__tip">只能上传png/jpg/pdf/xlsx格式附件</div>
    </el-upload>

  </div>
</template>

<script>
import axios from 'axios'
export default {
  data() {
    return {
      fileList: [
      ],
      uploadlist: [],
    }
  },
  methods: {
    //选择文件
    onChange(file, list) {
      this.uploadlist = list
      this.fileList = list;
      console.log(this.fileList);
    },
    //上传文件
    submitUpload() {
      // 定义一个数组用来判断是否有错误元素
      let arr = []
      // 对选择列表挨个上传
      this.uploadlist.forEach(async el => {
        let formData = new FormData()
        formData.append('files', el.raw)// 传文件
        formData.append('id', this.$route.query.id)
        let res = await this.$api.ImgFile.upload(defaultUrl+'/business/residentialQuarters/uploadAnnex', formData)
        if (res.data.code == 200) {
          this.$message({
            message: '文件上传成功',
            type: 'success'
          });
          // 清除文件列表
          this.$refs.upload.clearFiles();
          arr.push(true)
          this.$emit('Refresh', true)
        } else {
          arr.push(false)
        }
      })
      // 定义一个错误列表，如果有错误的就添加该元素
      let errList = []
      arr.forEach((el, i) => {
        if (!el) {
          errList.push(this.uploadlist[i])
        }
      })
      // 获取错误元素的名字，报错
      let text = []
      if (errList.length > 0) {
        errList.forEach(el => {
          text.push(el.name)
        })
        // 使用通知组件
        this.$notify.error({
          title: '上传错误',
          dangerouslyUseHTMLString: true,
          message: `${text.join(' <br /> ')}
                    <br />
                    <span class="err">以上文件上传失败，请尝试重新上传或联系管理员</span>
                    `,
          duration: 0
        });
        let err = document.querySelector('.err')
        err.style.color = 'red'
      }

    },
  }
}
</script>

<style lang="less" scoped></style>